package org.mat.sample.service.impl;

import org.mat.framework.core.exception.AssertUtils;
import org.mat.framework.lang.constant.DefaultErrors;
import org.mat.sample.dto.DispatchRequest;
import org.mat.sample.entity.LogisticsDispatch;
import org.mat.sample.entity.Order;
import org.mat.sample.enums.OrderStatus;
import org.mat.sample.mapper.LogisticsDispatchMapper;
import org.mat.sample.mapper.OrderMapper;
import org.mat.sample.service.LogisticsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class LogisticsServiceImpl implements LogisticsService {

    @Autowired
    OrderMapper orderMapper;

    @Autowired
    LogisticsDispatchMapper dispatchMapper;

    @Override
    @Transactional
    public void batchDispatch(DispatchRequest request) {
        request.getOrderIds().forEach(orderId -> {
            Order order = orderMapper.selectWithLock(orderId);
            AssertUtils.assertTrue(order.getCurrentStatus() != OrderStatus.PENDING, DefaultErrors.DEFAULT);

            orderMapper.updateStatus(orderId, OrderStatus.DISPATCHED);

            LogisticsDispatch logisticsDispatch = new LogisticsDispatch();
            logisticsDispatch.setOrderId(orderId);
            logisticsDispatch.setLogisticsCompany(request.getLogisticsCompany());
            dispatchMapper.insertDispatch(logisticsDispatch);
        });
    }

    @Override
    public List<Order> queryPendingOrders(String centerId) {
        List<Order> orderList = orderMapper.selectByCenterAndStatus(centerId,
                OrderStatus.PENDING);
        return orderList;
    }
}